#include "FileSystem.h"

namespace ISNW
{
namespace io
{
	FileSystem::FileSystem()
	{
		//! get current process directory
		c8 buf[MAX_PATH];
		ZeroMemory(buf,MAX_PATH);
		GetCurrentDirectory(MAX_PATH,(LPSTR)buf);
		curr_directory = buf;
		if(curr_directory[curr_directory.size()] != '\\')
		{
			curr_directory += "\\";
		}

		//! current resource directory
		curr_resource_dir = curr_directory + "media\\";
	}

	IReadFile* FileSystem::createreadfile(const c8* filename) const
	{
		core::string fname;
		if(doesfileexist(filename))
		{
			fname = filename;
		}
		else
		{
			fname = getfileincurrdir(filename);
			if(!doesfileexist(fname.c_str()))
			{
				fname = getfileinresourcedir(filename);
				if(!doesfileexist(fname.c_str()))
				{
					return 0;
				}
			}
		}

		return createReadFile(fname.c_str());
	}

	core::string FileSystem::getapplicationpath() const
	{
		return curr_directory;
	}

	core::string FileSystem::getresourcepath() const
	{
		return curr_resource_dir;
	}

	core::string FileSystem::getfilenamefrompath(const c8* path) const
	{
		core::string ret = path;

		ret.replace('/','\\');

		s32 pos = ret.reverse_search('\\');
		if(pos == -1) return ret;

		ret.erase(0,pos+1);

		return ret;
	}

	core::string FileSystem::getfileincurrdir(const c8* file) const
	{
		core::string path;
		core::string fpath = getfilenamefrompath(file);

		path = curr_directory + fpath;

		return path;
	}

	core::string FileSystem::getfileinresourcedir(const c8* file) const
	{
		core::string path;
		core::string fpath = getfilenamefrompath(file);

		path = curr_resource_dir + fpath;

		return path;
	}

	bool FileSystem::doesfileexist(const c8* file) const
	{
		HANDLE hfile = CreateFile(file,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);

		if(hfile == INVALID_HANDLE_VALUE) return false;

		CloseHandle(hfile);

		return true;
	}

} // end namespace io
} // end namespace ISNW